import { observable,computed, action, toJS } from 'mobx';
import * as api from '../../apis/plan/planProgramViewApi'
import {message} from 'antd'
import { WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
export default class PlanProgramViewStore {
    @observable loading = false;
    @observable tabSelectKey = "1";
    @observable isweek=''
    @observable ismonth=''
    @observable tabDatas = []
    //自定义显示列内容
    @observable fieldRows=[]
    @observable resourceid=''
    @observable resourcetype=''
    @observable resourcename=''
    @observable programid=''
    @observable programid2=''
    //默认计划设置原始数据 后端返回的 ，是一个二维数组 一维代表是哪一列，二维代表值
    @observable defaultDatas=[]
    //处理过后的默认计划显示数据，用于表格
    @observable planDefaultRows=[]
    //计划的列
    @observable planPreColumns=[]
    //审核人
    @observable auditids=''
    @observable auditList=''
    @observable managerid=''//直接上级id
    @observable managername=[] 
    @observable managermap={}
    //主页是否显示计划总结
    @observable isshowplan=''
    @observable isshowsummary=''

    //权限
    @observable auth={
        canedit:false,
        canview:false,
        canReference:false
    }

    //编辑计划模态框显示
    @observable editModal={
        isShow:false,
        editData:{} //编辑的对象
    }

    fieldNames=[]

    //请求模板设置回来的数据
    @observable result={

    }
    //没权限或者未开启时的提示
    @observable noDataMessage = ''
    //操作日志
    @observable logs=[]

    //同步功能参数
    @observable referenceParam={
        ids: '',
        names: "",
        subCompanyids_refence: "",
        programid: 0,
        operation: "doReference",
        programtype: "",
    }

    //按钮权限
    @observable buttonAuth={
        canSave:false,
        canShare:false,
        canDel:false,
    }

    @observable cubeLayoutParame = []

    @observable iscube = '0'
    @observable isopencube = ''

    @computed get cubeResourceType(){
        return this.tabSelectKey+""+this.resourcetype
    }

    @action("设置预览头")
    setPlanPreColumns(v){
        this.planPreColumns=v
    }

    @action("获取模板设置")
    getTemplateConfig=()=>{
        this.loading=true
        api.getTemplateConfig(this.getRequestParam()).then(action((data) => {
            
            if(data.api_status){
                this.result = data
                this.fieldRows = this.transFieldList2RowDatas(data.fieldlist)
                this.resourceid=data.resourceid
                this.resourcetype=data.resourcetype
                this.programid=data.programid
                this.programid2=data.programid2
                this.defaultDatas=data.datass
                this.fieldNames=data.fields
                this.auth.canedit = data.canedit
                this.auth.canReference = data.canReference
                this.auth.canview=data.canview
                this.auditids = data.auditids
                this.auditnames = data.auditnames
                this.auditList = data.auditList
                this.noDataMessage=''
                this.logs=data.logs
                this.referenceParam.subCompanyids_refence=data.subCompanyids_refence
                this.referenceParam.programid=data.programid
                this.isweek=data.isweek
                this.ismonth=data.ismonth
                this.managerid=data.managerid
                this.managername=data.managername
                this.managermap=data.managermap
                this.isshowsummary=data.isshowsummary
                this.isshowplan=data.isshowplan
                this.iscube=data.iscube
                this.isopencube = data.isopen
                if(!data.isopen)this.iscube=0
                this.getPlanDefaultData()
                this.setButtonAuth()
                this.genTabDatas()
            }else{
                this.noDataMessage = data.message
                this.setButtonAuth()
                this.isweek=data.isweek
                this.ismonth=data.ismonth
                this.genTabDatas()
                this.result.titlename="<a href='javaScript:openhrm("+this.resourceid+");' onclick='pointerXY(event);'>"+this.resourcename+"</a> "+getLabel(509153,"计划报告模板设置")
                // message.error('error')
            }
            this.loading=false
        })).catch((e)=>{
            message.error(e.msg || getLabel('383746','请求失败') )
        });

    }

    @action("根据ismonth和isweek生成tabdatas")
    genTabDatas(){
        const {ismonth,isweek} = this
        let tabDatas=[]
        if(ismonth){
            tabDatas.push(
                {
                    title: getLabel('20617','月报') ,
                    viewcondition: '1',
                    key: '1',
                  },
            )
        }
        if(isweek){
            tabDatas.push(
                {
                    title: getLabel('20619','周报'),
                    viewcondition: '2',
                    key: '2',
                  },
            )
        }
        if(ismonth && !isweek){
            this.tabSelectKey='1'
        }else if(!ismonth && isweek){
            this.tabSelectKey='2'
        }

        this.tabDatas=tabDatas;

    }

    //设置按钮权限
    setButtonAuth(){
        this.buttonAuth = {
            canDel:false,canShare:false,canSave:false
        }
        if(this.noDataMessage){
            return 
        }

        const {canedit,canReference,canview} = this.auth
        if(canedit){
            this.buttonAuth.canSave=true
            if(this.programid2 && this.programid2!="0"){
                this.buttonAuth.canDel=true
            }
        }

        if(canReference){
            this.buttonAuth.canShare=true
        }

    }


    @action("同步")
    doReference(){
        this.referenceParam.programtype = this.tabSelectKey
        api.doReference(this.referenceParam).then(action((data)=>{
            if(data.api_status){
                message.info(data.msg)
            }else{
                message.error(data.msg)
            }
        }))
    }

    @action("删除")
    deleteTemplate(){
        let deleteParam={
            resourceid:this.resourceid,
            resourcetype:this.resourcetype,
            programid:this.programid,
            programtype:this.tabSelectKey
        }

        api.deleteTemplate(deleteParam).then(action((data)=>{
            if(data.api_status){
                message.success(getLabel('30700','操作成功'))
                this.getTemplateConfig()
            }else{
                message.error(data.msg || getLabel('383746','请求失败'))
            }
        }))
    }


    //计算显示列的总宽度
    getShowColumnsTotalWidth=()=>{
        let res = ''
        let totalWidth1 = 0
        let totalWidth2 = 0
        this.fieldRows.map(v=>{
            if(v.isshow==1){
                totalWidth1 += parseInt(v.showwidth)
            }
            if(v.isshow2==1){
                totalWidth2 += parseInt(v.showwidth2)
            }
        })
        if(totalWidth2>100){
            res  = getLabel('510409','当前工作计划列总宽度超过百分之百，是否确认保存？') 
        }
        if(totalWidth1>100){
            res  = getLabel('510410','当前工作总结列总宽度超过百分之百，是否确认保存？') 
        }
        return res
    }

    //获取保存属性
    getSaveParam=()=>{
        let params = {}
        params.resourceid=this.resourceid
        params.resourcetype=this.resourcetype
        params.programid=this.result.mbTitle ?'':this.programid
        params.fieldRows=JSON.stringify(this.fieldRows)
        params.programtype=this.tabSelectKey
        params.isshowplan=this.isshowplan!='0'?"1":"0"
        params.isshowsummary=this.isshowsummary!='0'?"1":"0"
        params.iscube = this.iscube 
        let defaultRow=toJS(this.planDefaultRows)
        for(let i=0;i<defaultRow.length;i++){
            for(var r in defaultRow[i]){
                if(!defaultRow[i][r] || defaultRow[i][r] == 'null'){
                    defaultRow[i][r]=' '
                }
            }
        }
        
        params.planDefaultRows=JSON.stringify(defaultRow)
        //上级领导存成-1
        params.auditids=this.auditids
        let audits = params.auditids.split(',')
        if(audits.length>0 && audits[0]!='' &&audits.indexOf(this.managerid)>-1){
            audits[audits.indexOf(this.managerid)] = -1
            params.auditids = audits.join(",")
        }
        return params
    }

    @action("保存模板设置")
    saveTemplateConfig=()=>{
        this.loading=true
        api.saveTemplateConfig(this.getSaveParam()).then(action((data) => {
            if(data.api_status){
                this.getTemplateConfig()
                message.success(getLabel('30700','操作成功'))
            }else{
                message.error(data.message || getLabel('383746','请求失败'))
            }
            this.loading=false
        }));

    }

    //转换list属性成table row的属性
    transFieldList2RowDatas=(list)=>{
        let result =[]
        list.map((v,i)=>{
            result.push({
                id:i,//给行数据一个id，便于以后修改
                showname:v[0],
                fieldname:v[1],
                customname:v[2],isshow:v[3],showorder:v[4],showwidth:v[5],isshow2:v[6],showorder2:v[7],showwidth2:v[8],ismust:v[9],ismust2:v[10]
            })
        })
        return result

    }

    //获取请求参数
    getRequestParam=()=>{
        let param = {}
        param.programtype = this.tabSelectKey
        param.resourceid=this.resourceid
        param.resourcetype=this.resourcetype
        return param
    }

    //获取计划默认数据
    getPlanDefaultData=()=>{
        let defaultDatas = toJS(this.defaultDatas)
        let defaultRow = []
        
        if(defaultDatas && defaultDatas.length>0){
            for(let i=0;i<defaultDatas[0].length;i++){
                let row = {}
                row.id= defaultDatas[0][i]+Math.random()
                row.cate =  defaultDatas[0][i]
                row.name =  defaultDatas[1][i]
                row.begindate1 =  defaultDatas[2][i]
                row.enddate1 =  defaultDatas[3][i]
                row.days1 =  defaultDatas[4][i]
                row.target =  defaultDatas[5][i]
                row.begindate2 =  defaultDatas[6][i]
                row.enddate2 =  defaultDatas[7][i]
                row.days2 =  defaultDatas[8][i]
                row.finishrate =  defaultDatas[9][i]
                row.result =  defaultDatas[10][i]
                row.custom1 =  defaultDatas[11][i]
                row.custom2 =  defaultDatas[12][i]
                row.custom3 =  defaultDatas[13][i]
                row.custom4 =  defaultDatas[14][i]
                row.custom5 =  defaultDatas[15][i]
                defaultRow.push(row)
            }
            for(var r in defaultRow){
                if(defaultRow[r] == 'null'){
                    defaultRow[r]=''
                }
            }

            this.planDefaultRows = defaultRow;
        }
    }
    @action
    setState=(k,v)=>{
        this[k]=v
    }
    //初始化
    @action
    initForm = params => {
        this.cubeLoading=true
        api.getPlanSetupInit(params).then(action((result) => {
            if(result.status==1 && result.isopen === true){
                this.cubeLayoutParame = {...result.data};
                if(params.doback){
                    params.doback();
                }
                this.isopencube = true
            }else{
                this.isopencube = false
                this.cubeLoading=false
            }
        }));
    }
}
